package com.csdj.server.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @Author zyq
 * @Date 2023/2/13 8:45
 * @ClassName: WebSocketConfig
 * @Description: TODO
 * @Version 1.0
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 添加节点 配置 访问地址
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws/ep")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                //获取消息的 端点处理类
                StompHeaderAccessor accessor = MessageHeaderAccessor
                        .getAccessor(message, StompHeaderAccessor.class);
                //判断 是否是连接状态
                if(StompCommand.CONNECT.equals(accessor.getCommand())){
                    // Bear xxx
                    //从 前端页面 发起http 请求 拿到请求的头的 token 信息
                    String authToken = accessor
                            .getFirstNativeHeader("Auth-Token");
                    //截取 拿到token
                    String token = authToken.substring(tokenHead.length());
                    if(!StringUtils.isEmpty(token)){

                        //根据 token 拿到用户名
                        String userName = jwtTokenUtil.getUserNameFormToken(token);
                        if(!StringUtils.isEmpty(userName)){
                            //登录 加载
                            UserDetails userDetails = userDetailsService
                                    .loadUserByUsername(userName);
                            //判断 token 是否过期
                            if(jwtTokenUtil.validateToken(token,userDetails)){
                                //加载 authentication
                                UsernamePasswordAuthenticationToken authenticationToken =
                                        new UsernamePasswordAuthenticationToken(userDetails,
                                                null, userDetails.getAuthorities());
                                //重新 加载 security当中的用户信息
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                //设置 用户信息
                                accessor.setUser(authenticationToken);
                            }

                        }
                    }


                }

                return message;
            }
        });
    }

    /**
     * 配置 消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue");
    }
}
